package com.ck.hxc.controller;


import com.ck.hxc.Ifasrdemo;
import com.ck.hxc.JsonProcessor;
import com.ck.hxc.sdk.WebIATWS;
import com.google.gson.Gson;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket;
import org.apache.poi.util.StringUtil;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author hxc
 * @since 2025/1/21 11:03
 */
@Tag(name = "用户接口")
@Slf4j
@RestController
@RequestMapping("/sdk")
public class ControllerTest {

    public static String con;

    private static final String hostUrl = "https://iat-api.xfyun.cn/v2/iat"; //中英文，http url 不支持解析 ws/wss schema
    // private static final String hostUrl = "https://iat-niche-api.xfyun.cn/v2/iat";//小语种
    private static final String apiKey = "9a7cea5874ba2c2112c7aaf345de9df0"; //在控制台-我的应用-语音听写（流式版）获取
    private static final String apiSecret = "ZGUwYjAxYmQxYjU4MDJjZmIxOTYxNzMz"; //在控制台-我的应用-语音听写（流式版）获取
    private static final String appid = "8a5ce7ae"; //在控制台-我的应用获取
    private static String file = "C:\\Users\\48157\\Desktop\\a.wav"; // 中文
    public static final int StatusFirstFrame = 0;
    public static final int StatusContinueFrame = 1;
    public static final int StatusLastFrame = 2;
    public static final Gson json = new Gson();
    WebIATWS.Decoder decoder = new WebIATWS.Decoder();
    // 开始时间
    private static Date dateBegin = new Date();
    // 结束时间
    private static Date dateEnd = new Date();
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm:ss.SSS");

    @PostMapping("/upload")
    public String upload(@RequestParam("files") MultipartFile files) throws Exception {
        // 指定保存文件的本地路径
        String uploadDir = "D:/uploads/";  // 你可以根据实际情况更改路径
        // 获取文件原始文件名
        String fileName = files.getOriginalFilename();
        // 创建目标文件对象
        File dest = new File(uploadDir + fileName);
        // 创建上传目录（如果没有的话）
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }

        // 将文件保存到指定路径
        files.transferTo(dest);
        file = dest.getAbsolutePath();

        String authUrl = getAuthUrl(hostUrl, apiKey, apiSecret);
        OkHttpClient client = new OkHttpClient.Builder().build();
        //将url中的 schema http://和https://分别替换为ws:// 和 wss://
        String url = authUrl.toString().replace("http://", "ws://").replace("https://", "wss://");
        //System.out.println(url);
        Request request = new Request.Builder().url(url).build();
        // System.out.println(client.newCall(request).execute());
        //System.out.println("url===>" + url);
        WebIATWS webIATWS = new WebIATWS(file);
        WebSocket webSocket = client.newWebSocket(request, webIATWS);

        Thread.sleep(5000);
        System.out.println("1111111111111111111111"+con);
        return con;
    }



    public static String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception {
        URL url = new URL(hostUrl);
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
        StringBuilder builder = new StringBuilder("host: ").append(url.getHost()).append("\n").//
                append("date: ").append(date).append("\n").//
                append("GET ").append(url.getPath()).append(" HTTP/1.1");
        //System.out.println(builder);
        Charset charset = Charset.forName("UTF-8");
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(charset), "hmacsha256");
        mac.init(spec);
        byte[] hexDigits = mac.doFinal(builder.toString().getBytes(charset));
        String sha = Base64.getEncoder().encodeToString(hexDigits);

        //System.out.println(sha);
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);
        //System.out.println(authorization);
        HttpUrl httpUrl = HttpUrl.parse("https://" + url.getHost() + url.getPath()).newBuilder().//
                addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(charset))).//
                addQueryParameter("date", date).//
                addQueryParameter("host", url.getHost()).//
                build();
        return httpUrl.toString();
    }


    @PostMapping("/uploadSdk")
    public String uploadSdk(@RequestParam("files") MultipartFile files) throws Exception {
        // 指定保存文件的本地路径
        String uploadDir = "D:/uploads/";  // 你可以根据实际情况更改路径
        // 获取文件原始文件名
        String fileName = files.getOriginalFilename();
        // 创建目标文件对象
        File dest = new File(uploadDir + fileName);
        // 创建上传目录（如果没有的话）
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }

        // 将文件保存到指定路径
        files.transferTo(dest);
        Ifasrdemo.AUDIO_FILE_PATH = dest.getAbsolutePath();

        String s = Ifasrdemo.a1();
        return JsonProcessor.a2(s);

    }
}